import cookie from 'vue-cookies'
export default {
  state: {
    isCollapse: false,
    asidewidth: '140px',
    currentMenuName: 'overview',
    dynamicName: null,
    activeNav: null, // 活动菜单序号
    currentMenu: null,
    menu: {},
    suffixIndex: 0, // 有动态子菜单需要, 如4-1
  },
  mutations: {
    setCollapse (state,status) {
      state.isCollapse = status
      if (status){
        state.asidewidth = '64px'
      }else{
        state.asidewidth = '140px'
      }
    },
    setMenuName (state,name) {
      var suffixIndex = cookie.get('suffixIndex')
      if (suffixIndex == 0) {
        state.currentMenuName = name
      }else{
        state.currentMenuName = name+cookie.get('dynamicName')
      }
    },
    setIndex (state,args) {
      if(args.length > 1 ){
        state.dynamicName = args[1]
        cookie.set('dynamicName', args[1])
      }
      state.suffixIndex = args[0]
      cookie.set('suffixIndex', args[0])
      
    },
    setActiveNav (state,num) {
      // 判断一下 suffixIndex, 静态菜单都设置0, 动态的才设置
      var suffixIndex = cookie.get('suffixIndex')
      if (suffixIndex == 0) {
        state.activeNav = num
      }else{
        state.activeNav = num+'-'+suffixIndex
      }
      
    },
    getMenu (state) {
      if (cookie.get('menu')) {
        let menu = cookie.get('menu')
        state.menu = menu
      }
    },
    setMenu (state, val) {
      // vuex添加
      state.menu = val
      // cookie也添加
      cookie.set('menu', JSON.stringify(val))
    },
    clearMenu (state) {
      // 清除也一样 vuex和cookie都清除
      state.menu = {}
      cookie.remove('menu')
    },
    addMenu (state, router) {
      if (!cookie.get('menu')) {
        return
      }
      // 取出cookie数据 给vuex
      let menu = cookie.get('menu')
      state.menu = menu
      // 添加动态路由 主路由为App.vue
      let currentMenu = [
        {
          path: '/',
          component: () => import(`@/views/main`),
          children: []
        }
      ]
      // 如果是一级菜单 那么菜单名称肯定有路由 如果是二级菜单那么一级没有 二级有路由
      menu.employee.forEach(item => {
        if (item.children) {
          item.children = item.children.map(item => {
            item.component = () => import(`@/views/${item.url}`)
            return item
          })
          currentMenu[0].children.push(...item.children)
        } else {
          var temp_route = {
            path: '/employee/'+item.name,
            component: () => import('@/views/Employee/employee')
          }
          currentMenu[0].children.push(temp_route)
        }
      })
      // 添加动态路由
      router.addRoutes(currentMenu)
    },
    // 左侧栏是否水平展开
    collapseMenu (state) {
      state.isCollapse = !state.isCollapse
    }
  },
  actions: {}
}
